package com.kmxd.ams.controller.arrange;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kmxd.ams.client.archive.IArchiveFieldSvc;
import com.kmxd.ams.client.archive.dto.ArchiveFieldQueryDTO;
import com.kmxd.ams.client.archive.vo.ArchiveFieldListVO;
import com.kmxd.ams.client.arrange.IDocumentSvc;
import com.kmxd.ams.client.arrange.dto.*;
import com.kmxd.ams.client.arrange.vo.CheckEfileVO;
import com.kmxd.ams.client.arrange.vo.UploadImportDataVO;
import com.kmxd.ams.client.arrange.vo.UploadImportVO;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.common.enums.ArchOpEnum;
import com.kmxd.ams.core.common.enums.ArchStatusEnum;
import com.kmxd.ams.core.common.enums.LogLevelEnum;
import com.kmxd.ams.core.common.enums.LogTypeEnum;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.core.log.annotation.ArchLogParameter;
import com.kmxd.ams.core.log.annotation.ArchLogParameters;
import com.kmxd.ams.core.log.annotation.AutoLog;
import com.kmxd.ams.core.log.annotation.AutoLogs;
import com.kmxd.ams.core.result.R;
import com.kmxd.ams.core.result.ResultCode;
import com.kmxd.ams.core.util.ExcelUtil;
import com.kmxd.ams.core.util.SecurityUtil;
import com.kmxd.ams.infra.arrange.base.BaseBO;
import com.kmxd.ams.infra.arrange.entity.Document;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件级 前端控制器
 *
 * @author ZuoLG
 * @since 2022-07-20
 */
@RestController
@Slf4j
@Tag(name = "文件级")
@RequestMapping("/arrange/document")
@AllArgsConstructor
public class DocumentCtl {

  private IDocumentSvc documentSvc;
  private IArchiveFieldSvc archiveFieldSvc;

  /** 分页查询 */
  @Operation(summary = "分页查询")
  @RequestMapping("/selectPage")
  @AutoLog(module = "文件级", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.LOW, title = "分页查询")
  @ArchLogParameter(op = ArchOpEnum.PAGE, content = "分页查询")
  public R<Page<Document>> selectPage(Page reqPage, Document req) {
    return R.success(documentSvc.selectPage(reqPage, req), req);
  }

  /** 列表查询 */
  @Operation(summary = "列表查询")
  @RequestMapping("/selectList")
  @AutoLog(module = "文件级", type = LogTypeEnum.SYSTEM, level = LogLevelEnum.LOW, title = "列表查询")
  @ArchLogParameter(op = ArchOpEnum.LIST, content = "列表查询")
  public R<List<Document>> selectList(Document req) {
    return R.success(documentSvc.selectList(req));
  }

  /** 根据盒id查询盒内文件 */
  @Operation(summary = "根据盒id查询盒内文件")
  @GetMapping("/selectListByBoxIds")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.SYSTEM,
      level = LogLevelEnum.LOW,
      title = "根据盒id查询盒内文件")
  @ArchLogParameter(op = ArchOpEnum.LIST, content = "根据盒id查询盒内文件")
  public R<List<Document>> selectListByBoxIds(BaseBO req) {
    return R.success(documentSvc.selectListByBoxIds(req, true));
  }

  /** 根据案卷id查询案卷内文件 */
  @Operation(summary = "根据案卷id查询案卷内文件")
  @GetMapping("/selectListByVolIds")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.SYSTEM,
      level = LogLevelEnum.LOW,
      title = "根据案卷id查询案卷内文件")
  @ArchLogParameter(op = ArchOpEnum.LIST, content = "根据案卷id查询案卷内文件")
  public R<List<Document>> selectListByVolIds(BaseBO req) {
    return R.success(documentSvc.selectListByVolIds(req, true));
  }

  /** 根据项目id查询项目下的文件 */
  @Operation(summary = "根据项目id查询项目下的文件")
  @GetMapping("/selectListByProjIds")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.SYSTEM,
      level = LogLevelEnum.LOW,
      title = "根据项目id查询项目下的文件")
  @ArchLogParameter(op = ArchOpEnum.LIST, content = "根据项目id查询项目下的文件")
  public R<List<Document>> selectListByProjIds(BaseBO req) {
    return R.success(documentSvc.selectListByProjIds(req, true));
  }

  /** 新增 */
  @Operation(summary = "新增")
  @PostMapping("/add")
  @SaCheckPermission("arrange:document:add")
  @ArchLogParameters({
    @ArchLogParameter(op = ArchOpEnum.MANUAL_INIT),
    @ArchLogParameter(op = ArchOpEnum.ADD_ENTITY, content = "实体增加登记+1份")
  })
  @AutoLogs({
    @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.LOW, title = "新增"),
    @AutoLog(
        module = "文件级",
        type = LogTypeEnum.ARCHIVE_USE,
        level = LogLevelEnum.LOW,
        title = "新增",
        opType = "录入一条档案")
  })
  public R<Void> add(@Validated @RequestBody Document req) {
    req.setFondsId(
        ObjectUtil.isEmpty(req.getFondsId()) ? SecurityUtil.getFondsId() : req.getFondsId());
    documentSvc.add(req);
    return R.success();
  }

  /** 修改 */
  @Operation(summary = "修改")
  @PostMapping("/edit")
  @SaCheckPermission("arrange:document:edit")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "修改")
  @ArchLogParameter(op = ArchOpEnum.UPDATE, content = "修改元数据值")
  public R<Void> edit(@Validated @RequestBody Document req) {
    documentSvc.edit(req);
    return R.success();
  }

  /** 删除 */
  @Operation(summary = "删除")
  @PostMapping("/remove")
  @SaCheckPermission("arrange:document:remove")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "删除")
  @ArchLogParameter(op = ArchOpEnum.DELETE, content = "删除")
  public R<Void> remove(@Validated @RequestBody Document req) {
    documentSvc.remove(req);
    return R.success();
  }

  /** 查看 */
  @Operation(summary = "查看")
  @PostMapping("/view")
  @AutoLogs({
    @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.LOW, title = "查看"),
    @AutoLog(
        module = "文件级",
        type = LogTypeEnum.ARCHIVE_USE,
        level = LogLevelEnum.LOW,
        title = "查看",
        opType = "浏览")
  })
  @ArchLogParameter(op = ArchOpEnum.VIEW, content = "查看")
  public R<Document> view(@Validated @RequestBody Document req) {
    return R.success(documentSvc.view(req));
  }

  /** 数据导入 */
  @Operation(summary = "导入功能-数据导入")
  @PostMapping("/dataImport")
  @SneakyThrows
  public R<UploadImportDataVO> dataImport(
      @Validated @RequestBody UploadImportDataDTO req, HttpServletResponse response) {
    return R.success(documentSvc.importData(req));
  }

  @SneakyThrows
  @Operation(summary = "导入功能-文件上传")
  @PostMapping("/uploadImport")
  @AutoLog(
      module = "档案导入",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "文件上传")
  public R<UploadImportVO> uploadImport(
      @RequestParam("file") MultipartFile file,
      @RequestParam("archTypeId") Long archTypeId,
      @RequestParam("tableId") String tableId) {
    if (Objects.isNull(file)) {
      throw BizTipException.instance(ErrorCode.VALIDATE_ERROR, ResultCode.PARAM_MISS.getMessage());
    }
    UploadImportFileDTO req = new UploadImportFileDTO();
    req.setArchTypeId(archTypeId);
    req.setTableId(tableId);
    req.setFile(file);
    return R.success(documentSvc.importUpload(req));
  }

  /** 下载模板 */
  @Operation(summary = "导入功能-下载模板")
  @PostMapping("/downTemplate")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.MEDIUM, title = "下载模板")
  @SneakyThrows
  public void downTemplate(@RequestBody BaseBO req, HttpServletResponse response) {
    String filename = "模板文件" + "_" + System.currentTimeMillis() + ".xlsx";
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("UTF-8");
    response.setHeader(
        "Content-Disposition",
        "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
    ArchiveFieldQueryDTO queryDTO = BeanUtil.copyProperties(req, ArchiveFieldQueryDTO.class);
    List<ArchiveFieldListVO> fields = archiveFieldSvc.selectList(queryDTO);
    List<String> header =
        fields.stream().map(item -> item.getDbFieldName()).collect(Collectors.toList());
    List<Map<String, Object>> datas = Lists.newArrayList();
    List<String> keys = Lists.newArrayList();
    EasyExcel.write(response.getOutputStream())
        // 这里放入动态头
        .head(ExcelUtil.head(header))
        .sheet("模板")
        .doWrite(ExcelUtil.detail(datas, keys));
  }

  /** 导出 */
  @Operation(summary = "导出")
  @PostMapping("/export")
  @SaCheckPermission("arrange:document:export")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "导出")
  @ArchLogParameter(op = ArchOpEnum.DATA_EXPORT, content = "导出")
  @SneakyThrows
  public void export(@RequestBody DataExportDTO req, HttpServletResponse response) {
    String filename = "文件" + "_" + System.currentTimeMillis() + ".xlsx";
    List<Map<String, Object>> datas = documentSvc.selectExport(req);
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("UTF-8");
    response.setHeader(
        "Content-Disposition",
        "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));

    List<String> header =
        req.getFields().stream()
            .filter(item -> ObjectUtil.isNotEmpty(item.getDbFieldName()))
            .map(item -> item.getDbFieldName())
            .collect(Collectors.toList());
    List<String> keys =
        req.getFields().stream()
            .filter(item -> ObjectUtil.isNotEmpty(item.getDbFieldKey()))
            .map(item -> item.getDbFieldKey())
            .collect(Collectors.toList());
    EasyExcel.write(response.getOutputStream())
        // 这里放入动态头
        .head(ExcelUtil.head(header))
        .sheet("数据")
        .doWrite(ExcelUtil.detail(datas, keys));
  }

  /** 复制 */
  @Operation(summary = "复制")
  @PostMapping("/copy")
  @SaCheckPermission("arrange:document:copy")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "复制")
  public R<Void> copy(@Validated @RequestBody DocumentCopyDTO req) {
    req.setOpType(ArchOpEnum.COPY.getCode());
    documentSvc.copy(req);
    return R.success();
  }

  /** 移动 */
  @Operation(summary = "移动")
  @PostMapping("/move")
  @SaCheckPermission("arrange:document:move")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "移动")
  public R<Void> move(@Validated @RequestBody DocumentCopyDTO req) {
    req.setOpType(ArchOpEnum.MOVE.getCode());
    documentSvc.copy(req);
    return R.success();
  }

  /** 移动 */
  @Operation(summary = "移动到资料库")
  @PostMapping("/moveToNotArchive")
  @SaCheckPermission("arrange:document:moveToNotArchive")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "移动")
  public R<Void> moveToNotArchive(@Validated @RequestBody Document req) {
    req.setStatus(ArchStatusEnum.S8.getCode());
    documentSvc.changeStatus(req);
    return R.success();
  }

  /** 预归档 - 使用跟转不归档同样权限 */
  @Operation(summary = "预归档")
  @PostMapping("/moveToTakeArchive")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.ARCHIVE,
      level = LogLevelEnum.HIGH,
      title = "预归档")
  @SaCheckPermission("arrange:document:moveToNotArchive")
  public R<Void> moveToTakeArchive(@Validated @RequestBody Document req) {
    req.setStatus(ArchStatusEnum.S9.getCode());
    documentSvc.changeStatus(req);
    return R.success();
  }

  /** 移动 */
  @Operation(summary = "移动到整理库")
  @PostMapping("/moveToCollection")
  @SaCheckPermission("arrange:document:moveToCollection")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "移动")
  public R<Void> moveToCollection(@Validated @RequestBody Document req) {
    req.setStatus(ArchStatusEnum.S0.getCode());
    documentSvc.changeStatus(req);
    return R.success();
  }

  /** 清空电子文件 */
  @Operation(summary = "清空电子文件")
  @PostMapping("/removeAllEfile")
  @SaCheckPermission("arrange:document:removeAllEfile")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.ARCHIVE,
      level = LogLevelEnum.HIGH,
      title = "清空电子文件")
  public R<Boolean> removeAllEfile(@Validated @RequestBody BaseBO req) {
    return R.success(documentSvc.removeAllEfile(req));
  }

  /** 检查电子文件 */
  @Operation(summary = "检查电子文件")
  @PostMapping("/checkEfile")
  @SaCheckPermission("arrange:document:checkEfile")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.ARCHIVE,
      level = LogLevelEnum.MEDIUM,
      title = "检查电子文件")
  public R<List<CheckEfileVO>> checkEfile(@Validated @RequestBody BaseBO req) {
    return R.success(documentSvc.checkEfile(req));
  }

  /** */
  @Operation(summary = "拆离")
  @PostMapping("/detach")
  @SaCheckPermission("arrange:document:detach")
  @AutoLog(module = "档案整理", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.HIGH, title = "拆离")
  public R<Object> detach(@Validated @RequestBody DetachDTO req) {
    documentSvc.detach(req);
    return R.success();
  }

  /** 删除回收站数据 */
  @Operation(summary = "删除回收站数据")
  @PostMapping("/cleanTrash")
  @SaCheckPermission("arrange:document:cleanTrash")
  @AutoLog(
      module = "文件级",
      type = LogTypeEnum.ARCHIVE,
      level = LogLevelEnum.HIGH,
      title = "删除回收站数据")
  @ArchLogParameter(op = ArchOpEnum.DELETE_TRASH, content = "删除回收站数据")
  public R<Void> cleanTrash(@Validated @RequestBody BaseBO req) {
    documentSvc.cleanTrash(req);
    return R.success();
  }

  /** 数据还原 */
  @Operation(summary = "数据还原")
  @PostMapping("/recoveryData")
  @SaCheckPermission("arrange:document:recoveryData")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.LOW, title = "数据还原")
  @ArchLogParameter(op = ArchOpEnum.GO_BACK_TO_ARRANGE)
  public R<Void> recoveryData(@Validated @RequestBody BaseBO req) {
    documentSvc.recoveryData(req);
    return R.success();
  }

  /** 新增 */
  @Operation(summary = "数据保存校验")
  @GetMapping("/checkExist")
  //  @SaCheckPermission("arrange:document:checkExist")
  @AutoLog(module = "文件级", type = LogTypeEnum.ARCHIVE, level = LogLevelEnum.LOW, title = "数据保存校验")
  public R<Boolean> checkExist(Document req) {
    Document view = documentSvc.viewIgnoreDelFlag(req);
    if (Objects.isNull(view)) {
      throw BizTipException.instance(ErrorCode.DATA_NOT_SAVE_CAN_NOT_MOUNT, "数据未保存，不能进行挂载操作");
    }
    return R.success(Objects.nonNull(view));
  }
}
